package com._520it.wms.service.impl;

import com._520it.wms.domain.Role;
import com._520it.wms.mapper.RoleMapper;
import com._520it.wms.query.PageResult;
import com._520it.wms.query.QueryObject;
import com._520it.wms.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HASEE on 2017/11/14.
 */
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void saveOrUpdate(Role role, Long[] permissionIds, Long[] menuIds) {
        if (role.getId() != null) {
            //删除和角色的关联关系
            roleMapper.deleteRelactionWithPermission(role.getId());
            //删除和菜单的关联关系
            roleMapper.deleteRelactionWithMenu(role.getId());

            roleMapper.updateByPrimaryKey(role);
            //保存角色和权限的关联信息
            if (permissionIds != null) {
                for (Long permissionId : permissionIds) {
                    roleMapper.insertRelationWithPermission(role.getId(), permissionId);
                }
            }
            //保存角色和菜单的关联关系
            if (menuIds != null) {
                for (Long menuId : menuIds) {
                    roleMapper.insertRelationWithMenu(role.getId(), menuId);
                }
            }

        } else {//新增
            //1保存操作
            roleMapper.insert(role);
            //2保存角色和权限的关联信息
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelationWithPermission(role.getId(), permissionId);
            }
            //和系统菜单的关联关系
            for (Long menuId : menuIds) {
                roleMapper.insertRelationWithMenu(role.getId(), menuId);
            }

        }

    }

    @Override
    public void delete(Long id) {
        //1删除和权限的关联关系
        roleMapper.deleteRelactionWithPermission(id);
        //删除和系统菜单的关联关系
        roleMapper.deleteRelactionWithMenu(id);
        //删除自己
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int totalCount = roleMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult(qo.getCurrentPage(), qo.getPageSize());
        }
        //查询结果集
        List<Role> list = roleMapper.queryForList(qo);
        return new PageResult(qo.getCurrentPage(), qo.getPageSize(), list, totalCount);
    }

    @Override
    public ArrayList<String> queryByEmpId(Long empId) {

        return roleMapper.queryByEmpId(empId);
    }
}

